//
//  StatusCell.swift
//  weibo117
//
//  Created by 宋禹奇 on 15/7/4.
//  Copyright © 2015年 宋禹奇. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

protocol StatusCellDelegate: NSObjectProtocol {
    //选中照片的代理方法
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int)
}

/// 图片视图可重用标示符
private let YUPictureCellReuseIdentifier = "YUPictureCellReuseIdentifier"
///转发微博重用标示符
let YUStatusForwardCellIdentifier = "YUStatusForwardCellIdentifier"
///原创微博重用标示符
let YUStatusNormalCellIdentifier = "YUStatusNormalCellIdentifier"


class StatusCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {
   
    //照片代理
    var photoDelegate: StatusCellDelegate?
    //转发文字
    var forwardLabel: UILabel?
    
    var status: Status? {
        didSet {
            //设置转发微博文
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? " ") + ": " + (status?.retweeted_status?.text ?? "")
            //设置头像
//            if let urlString = status?.user?.profile_image_url {
//            
//                iconView.sd_setImageWithURL(NSURL(string: urlString))
//            
//            }
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            //微博认证
            vipIconView.image = status?.user?.verifiedImage
            
            //会员等级
            memberIconView.image = status?.user?.mbImage
            nameLabel.text = status?.user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = "来自 微博"
            contentLabel.text = status?.text
            
            //获取图片容器的size
            let result = calcPictureViewSize(status!)
            //宽高约束
            widthCons?.constant = result.viewSize.width
            heightCons?.constant = result.viewSize.height
            //顶部约束
            topCons?.constant = result.viewSize.height == 0 ? 0 : 12
            
            pictureLayout.itemSize = result.itemSize
            
            pictureView.reloadData()
        }
    }
 
    //重用标示符
    class func cellIdentifier(status: Status) -> String {
        return status.retweeted_status != nil ? YUStatusForwardCellIdentifier : YUStatusNormalCellIdentifier
    }
    
    //计算行高
    func rowHeight(status: Status) -> CGFloat {
    
        //给模型设置数值,调用didset方法
        self.status = status
        //更新布局
        layoutIfNeeded()
        //返回行高
        return CGRectGetMaxY(footerView.frame)
    }
    //记录数值约束
    func recordPictureViewCons(cons: [NSLayoutConstraint]) {
        
        // 宽高约束
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        //顶部约束
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
  
    }
    
    //数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = pictureView.dequeueReusableCellWithReuseIdentifier(YUPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = status!.picURLs![indexPath.item]
        
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //照片选中方法
        photoDelegate?.statusCellDidSelectedPhoto(self, photoIndex: indexPath.item)
    }
    
    ///  根据微博模型计算图片是的大小
    /**
    0. 没有图片，返回zero
    1. 单图会按照图片等比例显示
    2. 多图的图片大小固定
    3. 多图如果是4张，会按照 2 * 2 显示
    4. 多图其他数量，按照 3 * 3 九宫格显示
    */
    private func calcPictureViewSize(status: Status) -> (viewSize: CGSize, itemSize: CGSize) {
        
        let itemSize = CGSizeMake(90, 90)
        let margin: CGFloat = 10

//        0. 没有图片，返回zero
        let count = status.picURLs!.count ?? 0
        
        if count == 0 {
            return (CGSizeZero,itemSize)
        }
//        1. 只有一张图片
        if count == 1 {
        
            //在imageURLs数组中取出当前图片的urlString为缓存的key
            let key = status.picURLs![0].absoluteString
            
            //根据key 在缓存池中取出当前图片
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            //返回图片正常尺寸
            return (image.size, image.size)
        
        }
        
//        2. 多图如果是4张，会按照 2 * 2 显示
        
        if count == 4 {
        
            let wh = itemSize.width * 2 + margin
            
            return (CGSizeMake(wh, wh),itemSize)
        
        }
        
//        3. 多图其他数量，按照 3 * 3 九宫格显示
        let countRow = 3
        
        let row = (count - 1) / countRow + 1
        
        let w = itemSize.width * CGFloat(countRow) + margin * CGFloat(countRow - 1)
        
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)

        return (CGSizeMake(w, h),itemSize)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let screenWidth = UIScreen.mainScreen().bounds.width
        
        let topView = UIView()
        addSubview(topView)
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        topView.ff_AlignInner(ff_AlignType.TopRight, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
        //添加图片视图
        addSubview(pictureView)
        
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        //准备视图
        preparePictureView()
        

        
        //头像
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 22))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        
        //页脚视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))
        //测试用的
        //iconView.image = UIImage(named: "avatar")
    
    }
    
    private func preparePictureView(){
    
        //设置背景颜色
        pictureView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        //数据源
        pictureView.dataSource = self
        pictureView.delegate = self
        
        //注册可重用cell
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: YUPictureCellReuseIdentifier)
        
        //设置layout
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //配图容器的宽度约束
    private var widthCons: NSLayoutConstraint?
    
    //配图容器的高度约束
    private var heightCons: NSLayoutConstraint?
    
    //配图视图的顶部约束
    private var topCons: NSLayoutConstraint?
    
    lazy var iconView = UIImageView()
    lazy var nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    
    //图像视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    //底部视图
    lazy var footerView: StatusFooterView = StatusFooterView()
    

}

//配图
private class StatusPictureCell: UICollectionViewCell {

    //图像地址
    var imageURL: NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    //重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //设置图片的填充模式
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        
        addSubview(iconView)
        
        iconView.ff_Fill(self)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //懒加载
    lazy var iconView = UIImageView()

}

//底部视图
class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var forwardBtn: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    
    lazy var commentBtn: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)

    lazy var likeBtn: UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)
   


}
